const Router = require('koa-router');
const multer = require('@koa/multer');
const path = require('path');
const fs = require('fs');
const pool = require('../db');

const router = new Router();

// 文件上传配置
const upload = multer({
    dest: path.join(__dirname, '../uploads'),
    limits: { 
        fileSize: 50 * 1024 * 1024 // 50MB
    }
});

// SQLite数据库初始化（用于存储音频文件）
let sqlite3;
let db;
try {
    sqlite3 = require('sqlite3').verbose();
    const dbPath = path.join(__dirname, '../music.db');
    db = new sqlite3.Database(dbPath);
    db.serialize(() => {
        db.run(`CREATE TABLE IF NOT EXISTS audio_files (
            id INTEGER PRIMARY KEY AUTOINCREMENT,
            filename TEXT,
            mime TEXT,
            size INTEGER,
            data BLOB,
            created_at DATETIME DEFAULT CURRENT_TIMESTAMP
        )`);
    });
    console.log('✓ SQLite数据库初始化完成');
} catch (e) {
    console.warn('SQLite3未安装，音频文件将存储到文件系统');
}

/**
 * 完整音频上传接口 - 同时处理音频文件、歌名和原唱信息
 * POST /api/upload/complete
 * 参数：
 *   - audio: 音频文件
 *   - songName: 歌名
 *   - artistName: 原唱
 */
router.post('/api/upload/complete', upload.single('audio'), async (ctx) => {
    const connection = await pool.getConnection();
    
    try {
        await connection.beginTransaction();
        
        const { songName, artistName } = ctx.request.body;
        
        // 验证必填字段
        if (!ctx.file) {
            ctx.status = 400;
            ctx.body = { code: -1, message: '请选择音频文件' };
            return;
        }
        
        if (!songName || !artistName) {
            ctx.status = 400;
            ctx.body = { code: -1, message: '歌名和原唱不能为空' };
            return;
        }

        // 1. 处理原唱信息 - 检查是否已存在，不存在则创建
        let artistId;
        const [existingArtists] = await connection.execute(
            'SELECT id FROM songers WHERE name = ?', 
            [artistName]
        );
        
        if (existingArtists.length > 0) {
            artistId = existingArtists[0].id;
            console.log(`使用已存在的原唱: ${artistName} (ID: ${artistId})`);
        } else {
            const [artistResult] = await connection.execute(
                'INSERT INTO songers (name) VALUES (?)', 
                [artistName]
            );
            artistId = artistResult.insertId;
            console.log(`创建新原唱: ${artistName} (ID: ${artistId})`);
        }

        // 2. 处理音频文件上传
        let audioUrl;
        const file = ctx.file;
        
        if (db && sqlite3) {
            // 使用SQLite存储音频文件
            const mime = file.mimetype || 'audio/mpeg';
            const size = file.size || 0;
            const buffer = fs.readFileSync(file.path);
            
            const audioId = await new Promise((resolve, reject) => {
                db.run(
                    `INSERT INTO audio_files (filename, mime, size, data) VALUES (?, ?, ?, ?)`,
                    [file.originalname, mime, size, buffer],
                    function (err) {
                        if (err) return reject(err);
                        resolve(this.lastID);
                    }
                );
            });
            
            audioUrl = `http://localhost:3000/api/audio/${audioId}`;
            
            // 清理临时文件
            try { fs.unlinkSync(file.path); } catch (_) {}
            
        } else {
            // 使用文件系统存储
            const ext = path.extname(file.originalname);
            const newFilename = file.filename + ext;
            const uploadsDir = path.join(__dirname, '../uploads');
            
            if (!fs.existsSync(uploadsDir)) {
                fs.mkdirSync(uploadsDir, { recursive: true });
            }
            
            fs.renameSync(file.path, path.join(uploadsDir, newFilename));
            audioUrl = `http://localhost:3000/uploads/${newFilename}`;
        }

        // 3. 创建歌曲记录 - 使用实际的表结构
        const [songResult] = await connection.execute(
            'INSERT INTO songs (title, artist, song_url, artist_id) VALUES (?, ?, ?, ?)', 
            [songName, artistName, audioUrl, artistId]
        );
        
        const songId = songResult.insertId;
        
        await connection.commit();
        
        // 返回成功结果
        ctx.body = {
            code: 0,
            message: '音频上传成功',
            data: {
                songId: songId,
                songName: songName,
                artistId: artistId,
                artistName: artistName,
                audioUrl: audioUrl,
                filename: file.originalname,
                size: file.size
            }
        };
        
        console.log('音频上传完成:', {
            songId,
            songName,
            artistName,
            audioUrl
        });
        
    } catch (error) {
        await connection.rollback();
        console.error('音频上传失败:', error);
        
        // 清理可能的临时文件
        if (ctx.file && ctx.file.path) {
            try { fs.unlinkSync(ctx.file.path); } catch (_) {}
        }
        
        ctx.status = 500;
        ctx.body = { 
            code: -1, 
            message: '上传失败: ' + error.message 
        };
    } finally {
        connection.release();
    }
});

/**
 * 获取音频文件 - 支持范围请求
 */
router.get('/api/audio/:id', async (ctx) => {
    if (!db) { 
        ctx.status = 500; 
        ctx.body = 'SQLite数据库未初始化'; 
        return; 
    }
    
    const id = parseInt(ctx.params.id, 10);
    
    await new Promise((resolve) => {
        db.get(`SELECT mime, size, data FROM audio_files WHERE id = ?`, [id], (err, row) => {
            if (err || !row) {
                ctx.status = 404; 
                ctx.body = '音频文件不存在'; 
                return resolve();
            }
            
            const mime = row.mime || 'audio/mpeg';
            const size = row.size || (row.data ? row.data.length : 0);
            const buffer = row.data ? Buffer.from(row.data) : Buffer.alloc(0);
            
            ctx.set('Content-Type', mime);
            ctx.set('Accept-Ranges', 'bytes');
            ctx.set('Cache-Control', 'no-cache');

            // 支持范围请求（用于音频流播放）
            const range = ctx.headers.range;
            if (range && size > 0) {
                const parts = range.replace(/bytes=/, "").split("-");
                const start = parseInt(parts[0], 10);
                const end = parts[1] ? parseInt(parts[1], 10) : size - 1;
                const chunksize = (end - start) + 1;
                
                ctx.status = 206;
                ctx.set('Content-Range', `bytes ${start}-${end}/${size}`);
                ctx.set('Content-Length', chunksize);
                ctx.body = buffer.subarray(start, end + 1);
            } else {
                ctx.status = 200;
                ctx.set('Content-Length', size);
                ctx.body = buffer;
            }
            resolve();
        });
    });
});

/**
 * HEAD请求支持 - 获取音频文件信息
 */
router.head('/api/audio/:id', async (ctx) => {
    if (!db) { 
        ctx.status = 500; 
        return; 
    }
    
    const id = parseInt(ctx.params.id, 10);
    
    await new Promise((resolve) => {
        db.get(`SELECT mime, size FROM audio_files WHERE id = ?`, [id], (err, row) => {
            if (err || !row) {
                ctx.status = 404; 
                return resolve();
            }
            
            ctx.set('Content-Type', row.mime || 'audio/mpeg');
            ctx.set('Content-Length', row.size || 0);
            ctx.set('Accept-Ranges', 'bytes');
            ctx.set('Cache-Control', 'no-cache');
            ctx.status = 200;
            resolve();
        });
    });
});

module.exports = router;